package web

import (
	"fmt"
	"github.com/iris-contrib/middleware/cors"
	"github.com/kataras/iris/v12"
	"github.com/kataras/iris/v12/middleware/methodoverride"
	"github.com/kataras/iris/v12/middleware/pprof"
	"my_iris/global"
	"my_iris/web/routes"
	"my_iris/web/routes_api"
	"strings"
)

// 所有的路由
func Routes(app *iris.Application) {
	// [favicon]
	app.Favicon("./static/favicon.ico")

	// [注册视图]
	// Load the template files.
	tmpl := iris.HTML("./web/templates", ".html")
	// Enable re-build on local template files changes.
	tmpl.Reload(!global.SiteConf.IsProd) // 仅开发环境开启, 每次重新加载视图文件渲染
	// Register the view engine to the views, this will load the templates.
	app.RegisterView(tmpl)

	// [静态目录] static
	app.HandleDir("/static", "./static", iris.DirOptions{
		Gzip: false,
	})

	// 全局允许 options 请求
	app.AllowMethods(iris.MethodOptions)
	// [错误处理]
	app.OnErrorCode(iris.StatusNotFound, corsHandler, err404)
	app.OnErrorCode(iris.StatusInternalServerError, corsHandler, err500)
	// 禁止脚本访问
	app.UseGlobal(scriptForbidden)

	//HTTP Method Override
	mo := methodoverride.New(
		// Defaults to nil.
		methodoverride.SaveOriginalMethod("_originalMethod"),
		// Default values.
		// methodoverride.Methods(http.MethodPost),
		// methodoverride.Headers("X-HTTP-Method",
		//                        "X-HTTP-Method-Override",
		//                        "X-Method-Override"),
		// methodoverride.FormField("_method"),
		// methodoverride.Query("_method"),
	)
	// Register it with `WrapRouter`.
	app.WrapRouter(mo)

	// [注册路由]
	// 前台
	// http://{host}/
	app.PartyFunc("/", routes.Route)
	// 前台接口
	// http://{host}/api
	app.PartyFunc("/api", routes_api.Route)

	// [profiling] pprof
	if global.SiteConf.PProf {
		p := pprof.New()
		app.Any("/debug/pprof", p)
		app.Any("/debug/pprof/{action:path}", p)
	}
}

func err404(ctx iris.Context) {
	handleErrorCode(ctx, 404)
}

func err500(ctx iris.Context) {
	handleErrorCode(ctx, 500)
}

func handleErrorCode(ctx iris.Context, code int) {
	// ajax 访问, 返回json
	if ctx.IsAjax() {
		if ctx.Method() == iris.MethodGet ||
			ctx.Method() == iris.MethodPost ||
			ctx.Method() == iris.MethodPut ||
			ctx.Method() == iris.MethodPatch ||
			ctx.Method() == iris.MethodDelete {
			_, _ = ctx.JSON(iris.Map{
				"code": code,
				"msg":  "出错了",
			})
			return
		}
	}
	// 浏览器跳转, 返回错误页面
	if ctx.Method() == iris.MethodGet || ctx.Method() == iris.MethodPost {
		_ = ctx.View(fmt.Sprintf("_errors/%d.html", code))
		return
	}
}

//corsHandler
var corsHandler = cors.New(cors.Options{
	Debug:            false,
	AllowCredentials: true,
	AllowedOrigins:   []string{"*"}, // 允许通过的主机名称
	AllowedMethods: []string{
		"GET",
		"POST",
		"PUT",
		"PATCH",
		"DELETE",
		"OPTIONS",
		"HEAD",
	},
	AllowedHeaders: []string{
		"Origin",
		"Content-Type",
		"Cookie",
		"Accept",
		"Authorization",
		"Access-Control-Allow-Origin",
		"X-Requested-With",
	},
})

// 禁止手机端访问
func mobileForbidden(ctx iris.Context) {
	if ctx.IsMobile() {
		if ctx.IsAjax() {
			ctx.StatusCode(iris.StatusBadRequest)
			_, _ = ctx.JSON(iris.Map{"msg": "请在电脑端访问!"})
			return
		}
		_, _ = ctx.HTML(`<h1>请在电脑端访问！</h1>`)
		return
	}
	ctx.Next()
}

// 禁止脚本访问
func scriptForbidden(ctx iris.Context) {
	if strings.TrimSpace(strings.ToLower(ctx.GetHeader("User-Agent"))) == "" || ctx.IsScript() {
		ctx.StatusCode(iris.StatusForbidden)
		return
	}
	ctx.Next()
}
